<template>
  <div class="auth-container">
    <h2>
      <i :class="isRegistering ? 'fa-user-plus' : 'fa-sign-in-alt'" class="fas"></i>
      {{ isRegistering ? '创建新账户' : '欢迎登录系统' }}
    </h2>

    <div class="auth-form">
      <input type="text" 
             v-model="account" 
             :placeholder="isRegistering ? '设置用户名' : '请输入账号'">

      <input type="password" 
             v-model="password"
             :placeholder="isRegistering ? '设置密码' : '请输入密码'">

      <input v-if="isRegistering"
             type="password"
             v-model="confirmPassword"
             placeholder="请再次输入密码">

      <div v-if="authError" class="error-message show">{{ authError }}</div>

      <button @click="submitForm" :disabled="isSubmitting">
        {{ isRegistering ? '立即注册' : '登录系统' }}
      </button>
    </div>

    <p class="auth-message">
      {{ isRegistering ? '已有账户？' : '没有账户？' }}
      <span @click="toggleAuthMode">
        {{ isRegistering ? '立即登录' : '立即注册' }}
      </span>
    </p>
  </div>
</template>
  
<script>
export default {
  name: 'AuthForm',
  props: {
    authError: String,
    isSubmitting: Boolean
  },
  emits: ['login', 'register', 'update:authError'],
  data() {
    return {
      isRegistering: false,
      account: '',
      password: '',
      confirmPassword: ''
    }
  },
  methods: {
    validateForm() {
      if (this.isRegistering) {
        if (this.password !== this.confirmPassword) {
          return '两次输入的密码不一致'
        }
        if (this.password.length < 8) {
          return '密码至少需要8位字符'
        }
      }
      return null
    },
    watch: {
    authError(newVal) {
      if (newVal) {
        this.$emit('update:isLoggedIn', false)
      }
    }
  },
    submitForm() {
      const error = this.validateForm()
      if (error) {
        this.$emit('update:authError', error)
        return
      }

      if (this.isRegistering) {
        this.$emit('register', {
          username: this.account,
          password: this.password
        })
      } else {
        this.$emit('login', {
          account: this.account,
          password: this.password
        })
        // localStorage.setItem('account', this.account)
      }
    },
    toggleAuthMode() {
      this.isRegistering = !this.isRegistering
      this.$emit('update:authError', '')
    },
    logout() {
      localStorage.removeItem('account');
      this.$router.push('/login');
    }
  }
}
</script>